# 两数相加 链表
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
def create_linked_list(nums):
    """
    Create a singly-linked list from a list of numbers.

    :param nums: List[int] - A list of integers to create the linked list from.
    :return: ListNode - The head of the newly created linked list.
    """
    if not nums:
        return None

    head = ListNode(nums[0])
    current = head
    for num in nums[1:]:
        current.next = ListNode(num)
        current = current.next

    return head
def print_list(head):
    current = head
    while current is not None:
        print(current.val,end=' ')
        current = current.next

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: Optional[ListNode]
        :type l2: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        # 初始化一个哑节点(dummy node)，方便处理链表头为null的情况
        dummy = ListNode(0)
        current = dummy
        carry = 0  # 初始化进位为0

        # 遍历两个链表，直到它们都到达末尾
        while l1 is not None or l2 is not None or carry:
            val1 = l1.val if l1 is not None else 0
            val2 = l2.val if l2 is not None else 0

            # 计算当前位的和以及进位
            total = val1 + val2 + carry
            carry = total // 10
            current.next = ListNode(total % 10)
            current = current.next

            # 移动到链表的下一个节点
            if l1 is not None:
                l1 = l1.next
            if l2 is not None:
                l2 = l2.next

        # 返回哑节点的下一个节点作为结果链表的头节点
        return dummy.next
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
s = Solution()
print_list(s.addTwoNumbers(l1,l2))
